﻿using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.IO;

namespace JianZhangTool.statistics.excel
{
    public class ExcelOutput
    {
        /// <summary>
        /// 存储到文件
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static bool SaveIntoFile(string filename)
        {
            if (Main.Instance.GetRoomGuardInfos() == null)
            {
                return false;
            }
            try
            {
                XSSFWorkbook workbook = new XSSFWorkbook();
                // 创建表
                ISheet sheet = workbook.CreateSheet("1");
                // 写入头
                IRow headerRow = sheet.CreateRow(0);
                headerRow.CreateCell(0).SetCellValue("UID");
                headerRow.CreateCell(1).SetCellValue("用户名");
                headerRow.CreateCell(2).SetCellValue("曾用名");
                headerRow.CreateCell(3).SetCellValue("舰长次数");
                headerRow.CreateCell(4).SetCellValue("提督次数");
                headerRow.CreateCell(5).SetCellValue("总督次数");
                headerRow.CreateCell(6).SetCellValue("深渊次数");
                // 写入内容
                int index = 0;
                foreach (GuardInfo guardInfo in Main.Instance.GetRoomGuardInfos().GetInfoList())
                {
                    index++;
                    IRow dataRow = sheet.CreateRow(index);
                    dataRow.CreateCell(0).SetCellValue(guardInfo.uid);
                    dataRow.CreateCell(1).SetCellValue(guardInfo.uname);
                    string on_str = "";
                    foreach (string on in guardInfo.old_unames)
                    {
                        if (!on_str.Equals(""))
                        {
                            on_str += ",";
                        }
                        on_str += on;
                    }
                    dataRow.CreateCell(2).SetCellValue(on_str);
                    dataRow.CreateCell(3).SetCellValue(guardInfo.jianzhang_num);
                    dataRow.CreateCell(4).SetCellValue(guardInfo.tidu_num);
                    dataRow.CreateCell(5).SetCellValue(guardInfo.zongdu_num);
                    dataRow.CreateCell(6).SetCellValue(guardInfo.shenyuan_num);
                }
                // 写入文件
                FileStream fs = new FileStream(filename, FileMode.Create);
                try
                {
                    workbook.Write(fs);
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();
                    }
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
